var util = require('../../utils/util.js');
//获取应用实例
const app = getApp();
Page({
    data: {
        listData: [{
            tips: "请添加商品图片",
            src: "../static/add_bg.jpg",
            name: "",
            number: 1
        }],
        date: "",
        time: "",
        // 修改
        modify: false,
        modifyUrl: 'https://wechat.wuyuzhong.com/api/activity/update',
        editUrl: 'https://wechat.wuyuzhong.com/api/activity/create',
        active_id: '',
        // 修改结束
        setTypeMessage: "到达设定时间自动开奖",
		typeMessage: ["到达设定时间自动开奖", "3天内设定人数自动开奖", "3天内发起人手动开奖"],
        setType: ["按时间自动开奖", "按人数自动开奖", "手动开奖"],
        winType: 0,
        winNum: '',
        setingShows: false,
        // 高级功能
        explain: "", //抽奖说明
        copy: "", //一键复制
        introduce: "", //奖品介绍
        imgs: [], //奖品介绍图
        passwordShows: false,
        password: "" //口令
    },
    // 图片上传 截图
    updataThumb: function(e) {
        var index = e.currentTarget.dataset.index;
        wx.chooseImage({
            success(res) {
                const tempFilePaths = res.tempFilePaths[0];
                wx.navigateTo({
                    url: `../avatarUpload/upload/upload?src=${tempFilePaths}&index=${index}`,
                })
            }
        })
    },
    onShow: function() {
        if (app.globalData.testUrl0 != '') {
            var changeSrc = 'listData[0].src';
			var tips = 'listData[0].tips';
            this.setData({
                [changeSrc]: app.globalData.testUrl0,
				[tips]: '修改商品图片'
            })
        }
        if (app.globalData.testUrl1 != '') {
            var changeSrc = 'listData[1].src';
			var tips = 'listData[1].tips';
            this.setData({
                [changeSrc]: app.globalData.testUrl1,
				[tips]: '修改商品图片'
            })
        }
        if (app.globalData.testUrl2 != '') {
            var changeSrc = 'listData[2].src';
			var tips = 'listData[2].tips';
            this.setData({
                [changeSrc]: app.globalData.testUrl2,
				[tips]: '修改商品图片'
            })
        }
    },
    onLoad: function(index) {
        var inx = index.index;
        if (inx == 'modify') {
            var gloData = app.globalData.add;
            var introduceData = gloData.introduce;
            if (introduceData!='<div></div>') {
				if (introduceData.indexOf("<img") < 0) {//含有图片
					var introduceText = introduceData.split('</div><div>').join('\n');
					introduceText = introduceText.split('<div>').join('');
					introduceText = introduceText.split('</div>').join('');
				}
				else{//不含图片
					// 介绍文字 
					var introduceText = introduceData.match(/<div>([\s\S]*?)<img/)[1].split('</div><div>').join('\n');
					// 介绍图片
					var imgSrc = [];
					var imgReg = /<img.*?(?:>|\/>)/gi;
					//匹配src属性
					var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
					var arr = introduceData.match(imgReg);
					if (arr) {
						for (var i = 0; i < arr.length; i++) {
							var src = arr[i].match(srcReg);
							//获取图片地址
							if (src[1]) {
								// console.log('已匹配的图片地址' + (i + 1) + '：' + src[1]);
								imgSrc.push(src[1]);
							}
						}
					}
				}
                
            }
            var copy = gloData.copy;
            var date = gloData.open_at.slice(0, 10);
			var time = gloData.open_at.slice(-8, -3);
            var wintype = gloData.wintype;
            var winnum = gloData.open_num;
            var password = '';
            var atcive_id = gloData.id;
            var explain = gloData.explain;
            var listData = [{
                tips: "修改商品图片",
                src: gloData.thumb1,
                name: gloData.title1,
                number: gloData.num1
            }]
            if (gloData.title2) {
                listData.push({
                    tips: "修改商品图片",
                    src: gloData.thumb2,
                    name: gloData.title2,
                    number: gloData.num2
                })
            }
            if (gloData.title3) {
                listData.push({
                    tips: "修改商品图片",
                    src: gloData.thumb3,
                    name: gloData.title3,
                    number: gloData.num3
                })
            }
			
            this.setData({
                copy: copy,
                modify: true,
                listData: listData,
                date: date,
                time: time,
                active_id: atcive_id,
                explain: explain,
                password: password || '',
                winType: wintype,
                winNum: winnum,
                setTypeMessage: this.data.typeMessage[wintype],
				setingShows: introduceText != undefined || imgSrc != undefined || explain != '',
                introduce: introduceText || '',
                imgs: imgSrc || [],
				passwordShows: password != ''

            })
        } else {
            var thisTime = new Date();
            var thisYear = thisTime.getFullYear(); //年
            var thisMonth = thisTime.getMonth() + 1; //月
            var thisDate = thisTime.getDate() + 1; //日
            var thisHours = thisTime.getHours(); //时
            var thisMinutes = thisTime.getMinutes(); //分
            if (thisDate < 10) {
                thisDate = '0' + thisDate
            }
            if (thisHours < 10) {
                thisHours = '0' + thisHours
            }
            if (thisMinutes < 10) {
                thisMinutes = '0' + thisMinutes
            }
            var nowDay = thisYear + '-' + thisMonth + '-' + thisDate;
            var nowTime = thisHours + ':' + thisMinutes;
            this.setData({
                date: nowDay,
                time: nowTime
            })
            if (app.globalData.testUrl0 != '') {
                var changeSrc = 'listData[0].src';
                this.setData({
                    [changeSrc]: app.globalData.testUrl0
                })
            }
            if (app.globalData.testUrl1 != '') {
                var changeSrc = 'listData[1].src';
                this.setData({
                    [changeSrc]: app.globalData.testUrl1
                })
            }
            if (app.globalData.testUrl2 != '') {
                var changeSrc = 'listData[2].src';
                this.setData({
                    [changeSrc]: app.globalData.testUrl2
                })
            }
            this.setData({
                modify: false
            })
        }
    },
    // 添加奖品
    addPrize: function() {
        var length = this.data.listData.length;
        var arr = [];
        if (length < 3) {
            this.data.listData.push({
                tips: "请添加商品图片",
                src: "../static/add_bg.jpg",
                name: "",
                number: 1
            });
            this.setData({
                listData: this.data.listData
            });
        } else {
            wx.showToast({
                title: "最多添加3项",
            })
        }
    },
    // 奖品名称
    watchName: function(e) {
		if (e.detail.value.length > 20) {
			e.detail.value = e.detail.value.substring(0, 20)
		}
        var index = e.currentTarget.dataset.index;
        var changeData = 'listData[' + index + '].name';
        this.setData({
            [changeData]: e.detail.value
        });
    },
    // 奖品数量
    watchNumber: function(e) {
        var index = e.currentTarget.dataset.index;
        var changeData = 'listData[' + index + '].number';
        this.setData({
            [changeData]: e.detail.value
        });
    },
    // 高级功能开关
    switchBindchange: function(e) {
        this.setData({
            setingShows: e.detail.value
        });
    },
    // 口令开关
    kouling: function(e) {
        this.setData({
            passwordShows: e.detail.value
        });
    },
    // 开奖类型
    actioncnt: function() {
        var that = this;
        wx.showActionSheet({
            itemList: ["按时间自动开奖", "按人数自动开奖", "手动开奖"],
            success: function(res) {
                var typeMsg = that.data.typeMessage[res.tapIndex];
                that.setData({
                    setTypeMessage: typeMsg,
                    winType: res.tapIndex
                })
            },
            fail: function(res) {
            }
        })
    },
    // 日期选择
    bindDateChange: function(e) {
        this.setData({
            date: e.detail.value
        })
    },
    // 时间选择
    bindTimeChange: function(e) {
        this.setData({
            time: e.detail.value
        })
    },
    reduceNum: function(e) {
        var index = e.currentTarget.dataset.index;
        this.data.listData.splice(index, 1);
        this.setData({
            listData: this.data.listData,
        });
    },
    // 说明
    explainSet: function(e) {
        if (e.detail.value.length > 200) {
            e.detail.value = e.detail.value.substring(0, 200)
        }
        this.setData({
            explain: e.detail.value
        })
    },
    copySet: function(e) {
        if (e.detail.value.length > 20) {
            e.detail.value = e.detail.value.substring(0, 20)
        }
        this.setData({
            copy: e.detail.value
        })
    },
    // 介绍
    introduceSet: function(e) {
        if (e.detail.value.length > 200) {
            e.detail.value = e.detail.value.substring(0, 200)
        }
        this.setData({
            introduce: e.detail.value
        })
    },
    passwordSet: function(e) {
        if (e.detail.value.length > 20) {
            e.detail.value = e.detail.value.substring(0, 20)
        }
        this.setData({
            password: e.detail.value
        })
    },
    winNumber: function(e) {
        this.setData({
            winNum: e.detail.value
        })
    },
    // 上传提交
    btnPost1: function() {

        // var openid = "ojVOu4n_2Yyo1uFS2c9Y26sQC0fM";
        var imgSrc = ''
        for (var i = 0; i < this.data.imgs.length; i++) {
            imgSrc += '<img src="' + this.data.imgs[i] + '" style="width:100%"/>'
        }
        var title1 = "";
        var title2 = "";
        var title3 = "";
        var num1 = 0;
        var num2 = 0;
        var num3 = 0;
        var thumb1 = "";
        var thumb2 = "";
        var thumb3 = "";
        var wintype = this.data.winType;
        // .split('\n').join('</div><div>')
        var explain = this.data.explain;
		var introduce = '<div>' + this.data.introduce.split('\n').join('</div><div>') + imgSrc + '</div>';
        var password = this.data.password;
        var winNum = this.data.winNum;
        if (this.data.winNum == '') {
            winNum = 0;
        }
        var copy = this.data.copy;
        //num1 = parseInt(this.data.listData[0].number);
        if (this.data.listData.length == 1) {
            title1 = this.data.listData[0].name;
            num1 = parseInt(this.data.listData[0].number);
            thumb1 = this.data.listData[0].src;
            if (title1 == "") {
                wx.showToast({
                    title: '请输入奖品名称',
                    icon: 'none',
                    duration: 1000
                });
                return false;
            } else if (title1.length > 20) {
                wx.showToast({
                    title: '奖品名称已超过20字',
                    icon: 'none',
                    duration: 1000
                });
                return false;
            } else if (num1 == 0 || isNaN(num1)) {
                wx.showToast({
                    title: '请输入奖品数量',
                    icon: 'none',
                    duration: 1000
                });
                return false;
            } else if (thumb1 == '../static/add_bg.jpg') {
                wx.showToast({
                    title: '请添加奖品图片',
                    icon: 'none',
                    duration: 1000
                });
                return false;
            }
        } else if (this.data.listData.length == 2) {
            title1 = this.data.listData[0].name;
            num1 = parseInt(this.data.listData[0].number);
            thumb1 = this.data.listData[0].src;
            title2 = this.data.listData[1].name;
            num2 = parseInt(this.data.listData[1].number);
            thumb2 = this.data.listData[1].src;
            if (title1 == "" || title2 == "") {
                wx.showToast({
                    title: '请输入奖品名称',
                    icon: 'none',
                    duration: 1000
                });
                return false;
            } else if (title1.length > 20 || title2.length > 20) {
                wx.showToast({
					title: '奖品名称已超过20字',
                    icon: 'none',
                    duration: 1000
                });
                return false;
            } else if (num1 == 0 || isNaN(num1) || num2 == 0 || isNaN(num2)) {
                wx.showToast({
                    title: '请输入奖品数量',
                    icon: 'none',
                    duration: 1000
                });
                return false;
            } else if (thumb1 == '../static/add_bg.jpg' || thumb2 == '../static/add_bg.jpg') {
                wx.showToast({
                    title: '请添加奖品图片',
                    icon: 'none',
                    duration: 1000
                });
                return false;
            }
        } else if (this.data.listData.length == 3) {
            title1 = this.data.listData[0].name;
            num1 = parseInt(this.data.listData[0].number);
            thumb1 = this.data.listData[0].src;
            title2 = this.data.listData[1].name;
            num2 = parseInt(this.data.listData[1].number);
            thumb2 = this.data.listData[1].src;
            title3 = this.data.listData[2].name;
            num3 = parseInt(this.data.listData[2].number);
            thumb3 = this.data.listData[2].src;
            if (title1 == "" || title2 == "" || title3 == "") {
                wx.showToast({
                    title: '请输入奖品名称',
                    icon: 'none',
                    duration: 1000
                });
                return false;
            } else if (title1.length > 20 || title2.length > 20 || title3.length > 20) {
                wx.showToast({
					title: '奖品名称已超过20字',
                    icon: 'none',
                    duration: 1000
                });
                return false;
            } else if (num1 == 0 || isNaN(num1) || num2 == 0 || isNaN(num2) || num3 == 0 || isNaN(num3)) {
                wx.showToast({
                    title: '请输入奖品数量',
                    icon: 'none',
                    duration: 1000
                });
                return false;
            } else if (thumb1 == '../static/add_bg.jpg' || thumb2 == '../static/add_bg.jpg' || thumb3 == '../static/add_bg.jpg') {
                wx.showToast({
                    title: '请添加奖品图片',
                    icon: 'none',
                    duration: 1000
                });
                return false;
            }
        }
        if (wintype == 0) { //按时间自动开奖
            var setTime = Date.parse(this.data.date + ' ' + this.data.time);
            var thisTime = Date.parse(new Date());
            if (setTime < thisTime) {
                wx.showToast({
                    title: '开奖时间不能小于当前时间',
                    icon: 'none'
                })
                setTimeout(function() {

                    wx.hideToast()

                }, 2000)
                return false;
            }
        } else if (wintype == 1) { //按人数开奖
            if (winNum == 0 || isNaN(winNum)) {
                wx.showToast({
                    title: '请输入开奖人数',
                    icon: 'none',
                    duration: 1000
                });
                return false;
            }
        }
        wx.showToast({
            title: '正在提交数据',
            icon: 'loading'
        })
        util.wPost('activity/create', {
            title1: title1,
            title2: title2,
            title3: title3,
            num1: num1,
            num2: num2,
            num3: num3,
            thumb1: thumb1,
            thumb2: thumb2,
            thumb3: thumb3,
            wintype: wintype,
            explain: explain,
            introduce: introduce,
            password: password,
            copy: copy,
            open_at: this.data.date + ' ' + this.data.time + ':00' || '',
            open_num: winNum
        }).then((res) => {
			if (res.data.code==1){
				wx.showToast({
					title: res.data.msg,
					icon:'none'
				});
				return;
			}else{
				app.globalData.testUrl0 = '';
				app.globalData.testUrl1 = '';
				app.globalData.testUrl2 = '';
				const redata = res.data;
				//do something
				// 跳转详情页
				var infoId = redata.data.id;
				wx.showToast({
					title: redata.msg,
				});
				setTimeout(function () {
					wx.redirectTo({
						url: "../activity/activity?key=" + infoId
					})
				}, 1000)
			}
            
        })
    },
    // 更新提交
    btnPost2: function() {
        // var openid = "ojVOu4n_2Yyo1uFS2c9Y26sQC0fM";
        var imgSrc = ''
        for (var i = 0; i < this.data.imgs.length; i++) {
            imgSrc += '<img src="' + this.data.imgs[i] + '" />'
        }
        var title1 = "";
        var title2 = "";
        var title3 = "";
        var num1 = 0;
        var num2 = 0;
        var num3 = 0;
        var thumb1 = "";
        var thumb2 = "";
        var thumb3 = "";
        var wintype = this.data.winType;
        var explain = this.data.explain;
        var introduce = '<div>' + this.data.introduce + imgSrc + '</div>';
        var password = this.data.password;
        var winNum = this.data.winNum;
        if (this.data.winNum == '') {
            winNum = 0;
        }
        var copy = this.data.copy;
        if (this.data.listData.length == 1) {
            title1 = this.data.listData[0].name;
            num1 = parseInt(this.data.listData[0].number);
            thumb1 = this.data.listData[0].src;
            if (title1 == "") {
                wx.showToast({
                    title: '请输入奖品名称',
                    icon: 'none',
                    duration: 1000
                });
                return false;
            } else if (title1.length > 20) {
                wx.showToast({
					title: '奖品名称已超过20字',
                    icon: 'none',
                    duration: 1000
                });
                return false;
            } else if (num1 == 0 || isNaN(num1)) {
                wx.showToast({
                    title: '请输入奖品数量',
                    icon: 'none',
                    duration: 1000
                });
                return false;
            } else if (thumb1 == '../static/add_bg.jpg') {
                wx.showToast({
                    title: '请添加奖品图片',
                    icon: 'none',
                    duration: 1000
                });
                return false;
            }
        } else if (this.data.listData.length == 2) {
            title1 = this.data.listData[0].name;
            num1 = parseInt(this.data.listData[0].number);
            thumb1 = this.data.listData[0].src;
            title2 = this.data.listData[1].name;
            num2 = parseInt(this.data.listData[1].number);
            thumb2 = this.data.listData[1].src;
            if (title1 == "" || title2 == "") {
                wx.showToast({
                    title: '请输入奖品名称',
                    icon: 'none',
                    duration: 1000
                });
                return false;
            } else if (title1.length > 20 || title2.length > 20) {
                wx.showToast({
					title: '奖品名称已超过20字',
                    icon: 'none',
                    duration: 1000
                });
                return false;
            } else if (num1 == 0 || isNaN(num1) || num2 == 0 || isNaN(num2)) {
                wx.showToast({
                    title: '请输入奖品数量',
                    icon: 'none',
                    duration: 1000
                });
                return false;
            } else if (thumb1 == '../static/add_bg.jpg' || thumb2 == '../static/add_bg.jpg') {
                wx.showToast({
                    title: '请添加奖品图片',
                    icon: 'none',
                    duration: 1000
                });
                return false;
            }
        } else if (this.data.listData.length == 3) {
            title1 = this.data.listData[0].name;
            num1 = parseInt(this.data.listData[0].number);
            thumb1 = this.data.listData[0].src;
            title2 = this.data.listData[1].name;
            num2 = parseInt(this.data.listData[1].number);
            thumb2 = this.data.listData[1].src;
            title3 = this.data.listData[2].name;
            num3 = parseInt(this.data.listData[2].number);
            thumb3 = this.data.listData[2].src;
            if (title1 == "" || title2 == "" || title3 == "") {
                wx.showToast({
                    title: '请输入奖品名称',
                    icon: 'none',
                    duration: 1000
                });
                return false;
            } else if (title1.length > 20 || title2.length > 20 || title3.length > 20) {
                wx.showToast({
					title: '奖品名称已超过20字',
                    icon: 'none',
                    duration: 1000
                });
                return false;
            } else if (num1 == 0 || isNaN(num1) || num2 == 0 || isNaN(num2) || num3 == 0 || isNaN(num3)) {
                wx.showToast({
                    title: '请输入奖品数量',
                    icon: 'none',
                    duration: 1000
                });
                return false;
            } else if (thumb1 == '../static/add_bg.jpg' || thumb2 == '../static/add_bg.jpg' || thumb3 == '../static/add_bg.jpg') {
                wx.showToast({
                    title: '请添加奖品图片',
                    icon: 'none',
                    duration: 1000
                });
                return false;
            }
        }
        if (wintype == 0) { //按时间自动开奖
            var setTime = Date.parse(this.data.date + ' ' + this.data.time);
            var thisTime = Date.parse(new Date());
            if (setTime < thisTime) {
                wx.showToast({
                    title: '开奖时间不能小于当前时间',
                    icon: 'none'
                })
                setTimeout(function() {
                    wx.hideToast()
                }, 2000)
                return false;
            }
        } else if (wintype == 1) { //按人数开奖
            if (winNum == 0 || isNaN(winNum)) {
                wx.showToast({
                    title: '请输入开奖人数',
                    icon: 'none',
                    duration: 1000
                });
                return false;
            }
        }
        wx.showToast({
            title: '正在提交数据',
            icon: 'loading'
        })

        util.wPost('activity/update', {
            title1: title1,
            title2: title2,
            title3: title3,
            num1: num1,
            num2: num2,
            num3: num3,
            thumb1: thumb1,
            thumb2: thumb2,
            thumb3: thumb3,
            wintype: wintype,
            explain: explain,
            introduce: introduce,
            password: password,
            copy: copy,
            open_at: this.data.date + ' ' + this.data.time + ':00' || '',
            open_num: winNum,
            id: this.data.active_id
        }).then((res) => {
			if (res.data.code == 1) {
				wx.showToast({
					title: res.data.msg,
					icon: 'none'
				});
				return;
			} else {
            app.globalData.testUrl0 = '';
            app.globalData.testUrl1 = '';
            app.globalData.testUrl2 = '';
            const redata = res.data;
            //do something
            var infoId = redata.data.id;
            wx.showToast({
                title: redata.msg,
            });
            setTimeout(function() {
                wx.redirectTo({
                    url: "../activity/activity?key=" + infoId
                })
            }, 1000)}
        })
    },
    busCoo: function() {
        wx.navigateTo({
            url: '../busCoo/busCoo'
        })
    },
    upconfirm: function() {
        this.up();
    },
    // 上传图片
    chooseImg: function(e) {
        var that = this;
        var imgs = this.data.imgs;
        var num = wx.getStorageSync('accessToken');
        if (imgs.length >= 9) {
            this.setData({
                lenMore: 1
            });
            setTimeout(function() {
                that.setData({
                    lenMore: 0
                });
            }, 2500);
            return false;
        }
        wx.chooseImage({
            // count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function(res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                var tempFilePaths = res.tempFilePaths;
                var imgs = that.data.imgs;
                for (var i = 0; i < tempFilePaths.length; i++) {
                    wx.uploadFile({
                        url: 'https://wechat.wuyuzhong.com/api/activity/upload', //仅为示例，非真实的接口地址
                        filePath: tempFilePaths[i],
                        name: 'giftImg',
                        header: {
                            'Content-Type': 'application/json',
                            'Accept': 'application/json',
                            'Authorization': num
                        },
                        formData: {},
                        success(response) {
                            var data = JSON.parse(response.data);
                            if (imgs.length >= 9) {
                                that.setData({
                                    imgs: imgs
                                });
                                return false;
                            } else {
                                imgs.push(data.data.path);
                            }
                            that.setData({
                                imgs: imgs
                            });
                        }
                    })
                }
            }
        });
    },
    // 删除图片
    deleteImg: function(e) {
        var imgs = this.data.imgs;
        var index = e.currentTarget.dataset.index;
        imgs.splice(index, 1);
        this.setData({
            imgs: imgs
        });
    },
    // 预览图片
    previewImg: function(e) {
        //获取当前图片的下标
        var index = e.currentTarget.dataset.index;
        //所有图片
        var imgs = this.data.imgs;
        wx.previewImage({
            //当前显示图片
            current: imgs[index],
            //所有图片
            urls: imgs
        })
    }
})